{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This file originates from\n",
    "https://github.com/MicrosoftDocs/PowerShell-Docs/blob/staging/build.ps1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "param(\n",
    "    [switch]$SkipCabs,\n",
    "    [switch]$ShowProgress\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Turning off the progress display, by default\n",
    "$global:ProgressPreference = 'SilentlyContinue'\n",
    "if ($ShowProgress) { $ProgressPreference = 'Continue' }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12\n",
    "$tempDir = [System.IO.Path]::GetTempPath()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Pandoc source URL\n",
    "$panDocVersion = \"2.7.3\"\n",
    "$pandocSourceURL = \"https://github.com/jgm/pandoc/releases/download/$panDocVersion/pandoc-$panDocVersion-windows-x86_64.zip\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "$pandocDestinationPath = New-Item (Join-Path $tempDir \"pandoc\") -ItemType Directory -Force\n",
    "$pandocZipPath = Join-Path $pandocDestinationPath \"pandoc-$panDocVersion-windows-x86_64.zip\"\n",
    "Invoke-WebRequest -Uri $pandocSourceURL -OutFile $pandocZipPath"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "Expand-Archive -Path $pandocZipPath -DestinationPath $pandocDestinationPath -Force\n",
    "$pandocExePath = Join-Path (Join-Path $pandocDestinationPath \"pandoc-$panDocVersion-windows-x86_64\") \"pandoc.exe\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install ThreadJob if not available\n",
    "$threadJob = Get-Module ThreadJob -ListAvailable\n",
    "if ($null -eq $threadjob) {\n",
    "    Install-Module ThreadJob -RequiredVersion 1.1.2 -Scope CurrentUser -Force\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Find the reference folder path w.r.t the script\n",
    "$ReferenceDocset = Join-Path $PSScriptRoot 'reference'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Go through all the directories in the reference folder\n",
    "$jobs = [System.Collections.Generic.List[object]]::new()\n",
    "$excludeList = 'module', 'media', 'docs-conceptual', 'mapping', 'bread', '7'\n",
    "Get-ChildItem $ReferenceDocset -Directory -Exclude $excludeList | ForEach-Object -Process {\n",
    "    $job = Start-ThreadJob -Name $_.Name -ArgumentList @($SkipCabs,$pandocExePath,$PSScriptRoot,$_) -ScriptBlock {\n",
    "        param($SkipCabs, $pandocExePath, $WorkingDirectory, $DocSet)\n",
    "\n",
    "        $tempDir = [System.IO.Path]::GetTempPath()\n",
    "        $workingDir = Join-Path $tempDir $DocSet.Name\n",
    "        $workingDir = New-Item -ItemType Directory -Path $workingDir -Force\n",
    "        Set-Location $WorkingDir\n",
    "\n",
    "        function Get-ContentWithoutHeader {\n",
    "            param(\n",
    "                $path\n",
    "            )\n",
    "\n",
    "            $doc = Get-Content $path -Encoding UTF8\n",
    "            $start = $end = -1\n",
    "\n",
    "            # search the first 30 lines for the Yaml header\n",
    "            # no yaml header in our docset will ever be that long\n",
    "\n",
    "            for ($x = 0; $x -lt 30; $x++) {\n",
    "                if ($doc[$x] -eq '---') {\n",
    "                    if ($start -eq -1) {\n",
    "                        $start = $x\n",
    "                    }\n",
    "                    else {\n",
    "                        if ($end -eq -1) {\n",
    "                            $end = $x + 1\n",
    "                            break\n",
    "                        }\n",
    "                    }\n",
    "                }\n",
    "            }\n",
    "            if ($end -gt $start) {\n",
    "                Write-Output ($doc[$end..$($doc.count)] -join \"`r`n\")\n",
    "            }\n",
    "            else {\n",
    "                Write-Output ($doc -join \"`r`n\")\n",
    "            }\n",
    "        }\n",
    "\n",
    "        $Version = $DocSet.Name\n",
    "        Write-Verbose -Verbose \"Version = $Version\"\n",
    "\n",
    "        $VersionFolder = $DocSet.FullName\n",
    "        Write-Verbose -Verbose \"VersionFolder = $VersionFolder\"\n",
    "\n",
    "        # For each of the directories, go through each module folder\n",
    "        Get-ChildItem $VersionFolder -Directory | ForEach-Object -Process {\n",
    "            $ModuleName = $_.Name\n",
    "            Write-Verbose -Verbose \"ModuleName = $ModuleName\"\n",
    "\n",
    "            $ModulePath = Join-Path $VersionFolder $ModuleName\n",
    "            Write-Verbose -Verbose \"ModulePath = $ModulePath\"\n",
    "\n",
    "            $LandingPage = Join-Path $ModulePath \"$ModuleName.md\"\n",
    "            Write-Verbose -Verbose \"LandingPage = $LandingPage\"\n",
    "\n",
    "            $MamlOutputFolder = Join-Path \"$WorkingDirectory\\maml\" \"$Version\\$ModuleName\"\n",
    "            Write-Verbose -Verbose \"MamlOutputFolder = $MamlOutputFolder\"\n",
    "\n",
    "            $CabOutputFolder = Join-Path \"$WorkingDirectory\\updatablehelp\" \"$Version\\$ModuleName\"\n",
    "            Write-Verbose -Verbose \"CabOutputFolder = $CabOutputFolder\"\n",
    "\n",
    "            if (-not (Test-Path $MamlOutputFolder)) {\n",
    "                New-Item $MamlOutputFolder -ItemType Directory -Force > $null\n",
    "            }\n",
    "\n",
    "            # Process the about topics if any\n",
    "            $AboutFolder = Join-Path $ModulePath \"About\"\n",
    "\n",
    "            if (Test-Path $AboutFolder) {\n",
    "                Write-Verbose -Verbose \"AboutFolder = $AboutFolder\"\n",
    "                Get-ChildItem \"$aboutfolder/about_*.md\" | ForEach-Object {\n",
    "                    $aboutFileFullName = $_.FullName\n",
    "                    $aboutFileOutputName = \"$($_.BaseName).help.txt\"\n",
    "                    $aboutFileOutputFullName = Join-Path $MamlOutputFolder $aboutFileOutputName\n",
    "\n",
    "                    $pandocArgs = @(\n",
    "                        \"--from=gfm\",\n",
    "                        \"--to=plain+multiline_tables\",\n",
    "                        \"--columns=75\",\n",
    "                        \"--output=$aboutFileOutputFullName\",\n",
    "                        \"--quiet\"\n",
    "                    )\n",
    "\n",
    "                    Get-ContentWithoutHeader $aboutFileFullName | & $pandocExePath $pandocArgs\n",
    "                }\n",
    "            }\n",
    "\n",
    "            try {\n",
    "                # For each module, create a single maml help file\n",
    "                # Adding warningaction=stop to throw errors for all warnings, erroraction=stop to make them terminating errors\n",
    "                New-ExternalHelp -Path $ModulePath -OutputPath $MamlOutputFolder -Force -WarningAction Stop -ErrorAction Stop\n",
    "\n",
    "                # For each module, create update-help help files (cab and helpinfo.xml files)\n",
    "                if (-not $SkipCabs) {\n",
    "                    $cabInfo = New-ExternalHelpCab -CabFilesFolder $MamlOutputFolder -LandingPagePath $LandingPage -OutputFolder $CabOutputFolder\n",
    "\n",
    "                    # Only output the cab fileinfo object\n",
    "                    if ($cabInfo.Count -eq 8) { $cabInfo[-1].FullName }\n",
    "                }\n",
    "            }\n",
    "            catch {\n",
    "                Write-Error -Message \"PlatyPS failure: $ModuleName -- $Version\" -Exception $_\n",
    "            }\n",
    "        }\n",
    "\n",
    "        Remove-Item $workingDir -Force -ErrorAction SilentlyContinue\n",
    "    }\n",
    "    Write-Verbose -Verbose \"Started job for $($_.Name)\"\n",
    "    $jobs += $job\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "$null = $jobs | Wait-Job"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Variable to collect any errors in during processing\n",
    "$allErrors = [System.Collections.Generic.List[string]]::new()\n",
    "foreach ($job in $jobs) {\n",
    "    Write-Verbose -Verbose \"$($job.Name) output:\"\n",
    "    if ($job.Verbose.Count -gt 0) {\n",
    "        foreach ($verboseMessage in $job.Verbose) {\n",
    "            Write-Verbose -Verbose $verboseMessage\n",
    "        }\n",
    "    }\n",
    "\n",
    "    if ($job.State -eq \"Failed\") {\n",
    "        $allErrors += \"$($job.Name) failed due to unhandled exception\"\n",
    "    }\n",
    "\n",
    "    if ($job.Error.Count -gt 0) {\n",
    "        $allErrors += \"$($job.Name) failed with errors:\"\n",
    "        $allErrors += $job.Error.ReadAll()\n",
    "    }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# If the above block, produced any errors, throw and fail the job\n",
    "if ($allErrors.Count -gt 0) {\n",
    "    $allErrors\n",
    "    throw \"There are errors during platyPS run!`nPlease fix your markdown to comply with the schema: https://github.com/PowerShell/platyPS/blob/master/platyPS.schema.md\"\n",
    "}"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "main_language": "powershell",
   "notebook_metadata_filter": "-all"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
